﻿using System.Security.Claims;
using Devonline.Core;
using Microsoft.AspNetCore.Authentication.BearerToken;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;

namespace Gateway.Controllers;

[Route("api/[controller]")]
[ApiController]
public class AccountController(ILogger<AccountController> logger) : ControllerBase
{
    private readonly ILogger<AccountController> _logger = logger;

    [AllowAnonymous]
    [HttpGet("GetParameters")]
    public async Task<IResult> GetParametersAsync()
    {
        _logger.LogInformation("user get parameters");
        await Task.CompletedTask;
        return Results.Ok(new
        {
            // 这里可以返回一些公共参数
            // 例如：版本号、系统时间等
            Version = "1.0.0",
            ServerTime = DateTime.UtcNow.ToString("yyyy-MM-dd HH:mm:ss")
        });
    }

    [AllowAnonymous]
    [HttpGet("login")]
    public IResult Login()
    {
        _logger.LogInformation("user will login");
        var claims = new[] {
            new Claim("sub", KeyGenerator.GetStringKey()),
            new Claim("auth", true.ToString()),
            new Claim("foreignTrade-dms", true.ToString()),
            new Claim(ClaimTypes.Name, KeyGenerator.GetStringKey()),
            new Claim(nameof(ClaimTypes.Name), KeyGenerator.GetStringKey())
        };

        //// 创建签名密钥
        //var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("devonlinededevonlinedevonlinevonline"));
        //var credentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
        //var token = new JwtSecurityToken(
        //    issuer: "gateway",
        //    audience: "foreignTrade",
        //    claims: claims,
        //    expires: DateTime.Now.AddHours(1),
        //    signingCredentials: credentials
        //);
        //return Ok(new { Token = new JwtSecurityTokenHandler().WriteToken(token) });

        return Results.SignIn(
            new ClaimsPrincipal(new ClaimsIdentity(claims, BearerTokenDefaults.AuthenticationScheme)),
            new Microsoft.AspNetCore.Authentication.AuthenticationProperties
            {
                IsPersistent = true,
                ExpiresUtc = DateTimeOffset.UtcNow.AddMinutes(30)
            },
            authenticationScheme: BearerTokenDefaults.AuthenticationScheme);
    }
}